package com.seari.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Period;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TimeZone;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.seari.Utils.DateUtils;
import com.seari.bean.PersonInfoBean;
import com.seari.bean.PlanShiftInfoBean;
import com.seari.bean.ReqPlanShiftBean;
import com.seari.mapper.PerSonInfoMapper;
import com.seari.mapper.PlanShiftInfoMapper;

@Service
public class PlanShiftInfoServiceImpl implements PlanShiftInfoService
{

	@Autowired
	PlanShiftInfoMapper planShiftInfoMapper;

	@Autowired
	PerSonInfoMapper perSonInfoMapper;

	@Override
	public void insertPlanShiftInfo(List<PlanShiftInfoBean> bean)
	{
		planShiftInfoMapper.insertPlanShiftInfo(bean);
	}

	@Override
	public int checkPanShiftInfoExist(String planShiftDate, String expirationDate)
	{
		return planShiftInfoMapper.checkPanShiftInfoExist(planShiftDate, expirationDate);
	}

	@Override
	public List<Object> fetchPlanShiftInfoList(ReqPlanShiftBean bean)
	{
		String onsetDate = bean.getReqShiftDate(); // 请求日期 起
		String expirationDate = bean.getReqShiftEndDate(); // 请求日期 止

		List<PersonInfoBean> existPlanShiftInfoList = perSonInfoMapper.getExistPlanShiftInfoList(onsetDate,
				expirationDate);

		if (bean.getPlanShiftType().equals("customWeek"))
		{
			// 组装周排班数据

			Map<String, List<PersonInfoBean>> classify = new HashMap<>();

			// 按照岗位对人员分类
			for (PersonInfoBean personInfoBean : existPlanShiftInfoList)
			{

				String shiftInfo = personInfoBean.getShiftInfoBean().getPlanShiftInfo();
				List<String> shiftInfoList = Arrays.asList(shiftInfo.split(","));
				personInfoBean.setShiftInfo(shiftInfoList);

				if (classify.containsKey(personInfoBean.getPostInfo()))
				{
					classify.get(personInfoBean.getPostInfo()).add(personInfoBean);
				} else
				{
					List<PersonInfoBean> list = new ArrayList<>();
					list.add(personInfoBean);
					classify.put(personInfoBean.getPostInfo(), list);
				}
			}

			List<Object> res = assemblyData(classify);
			String jsonString = JSON.toJSONString(res);
			System.out.println(jsonString);
			return res;
		} else
		{
			
			Map<String, List<PersonInfoBean>> classify = new HashMap<>();
			long curr = System.currentTimeMillis();
			// 获取截取天数
			Map<String, Integer> acquireCutLen = this.acquireCutLen(onsetDate, expirationDate);
			int onsetCutLen = acquireCutLen.get("onsetCutLen"); // 月头天数
			int expirationCutLen = acquireCutLen.get("expirationCutLen"); // 月末天数

			// 组装月排班数据
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Calendar c_begin = new GregorianCalendar();
			Calendar c_end = new GregorianCalendar();
			try
			{
				c_end.setTime(sdf.parse(expirationDate));
				Date onsetDateParse = sdf.parse(onsetDate);

				for (PersonInfoBean personInfoBean : existPlanShiftInfoList)
				{
					int j = 0;
					String[] planShift = personInfoBean.getShiftInfoBean().getPlanShiftInfo().split(","); // 获取人员的排班
					String[] planShiftDate = personInfoBean.getShiftInfoBean().getPlanShiftDate().split(","); // 获取人员的排班时间
					int len = planShiftDate.length;
					List<String> shift = new ArrayList<String>();
					
					c_begin.setTime(onsetDateParse);
					
					int count = 0;
					while (c_begin.before(c_end))
					{
						String psd = planShiftDate[count];
						String format = sdf.format(c_begin.getTime());
						if (format.equals(psd))
						{
							for (int k = 0; k < 7; k++, j++)
							{
								shift.add(planShift[j]);
							}
							c_begin.add(Calendar.DATE, 7);
							if (count + 1 < len)
							{
								count++;
							}
						} else
						{
							for (int k = 0; k < 7; k++)
							{
								shift.add("X");
							}
							c_begin.add(Calendar.DATE, 7);
							continue;
						}
					}
					
					//去掉月初多余天的数据
					for (int i = 0; i < onsetCutLen; i++)
					{
						shift.remove(0);
					}

					//去掉月末多余天的数据
					for (int i = 0; i < expirationCutLen; i++)
					{
						shift.remove(shift.size() - 1);
					}

					personInfoBean.setShiftInfo(shift);
					
					if (classify.containsKey(personInfoBean.getPostInfo()))
					{
						classify.get(personInfoBean.getPostInfo()).add(personInfoBean);
					} else
					{
						List<PersonInfoBean> list = new ArrayList<>();
						list.add(personInfoBean);
						classify.put(personInfoBean.getPostInfo(), list);
					}

				}
			} catch (ParseException e)
			{
				e.printStackTrace();
			}
			
			List<Object> res = assemblyData(classify);
			String jsonString = JSON.toJSONString(res);
			System.out.println(jsonString);
			System.out.println("耗时：（毫秒）" + (System.currentTimeMillis() - curr));
			return res;
		}
	}
	
	/**
	 * 组装数据
	 * @param classify
	 * @return
	 */
	public List<Object> assemblyData(Map<String, List<PersonInfoBean>> classify) {
		List<Object> res = new ArrayList<>();
		Iterator<Entry<String, List<PersonInfoBean>>> iterator = classify.entrySet().iterator();
		while (iterator.hasNext())
		{
			Map<String, Object> item = new HashMap<>();
			Entry<String, List<PersonInfoBean>> next = iterator.next();
			item.put("dept", next.getKey());
			item.put("data", next.getValue());
			res.add(item);
		}
		return res;
	}

	public Map<String, Integer> acquireCutLen(String onsetDate, String expirationDate)
	{
		Map<String, Integer> res = new HashMap<>();
		int onsetMonthDay = DateUtils.getDaysOfMonth(onsetDate) + 1; // 获取起始日期月份的天数

		int onsetCutLen = 0;
		int expirationCutLen = 0;

		String[] onsetDateArry = onsetDate.split("-");
		String[] expirationDateArry = expirationDate.split("-");

		int onsetDateDay = Integer.valueOf(onsetDateArry[2]);

		int expirationDateDay = Integer.valueOf(expirationDateArry[2]);

		// 起始日期是一号不用截取
		// 起始日期月份天数 - 起始日期
		if (onsetDateDay == 1)
		{
			onsetCutLen = 0;
		} else
		{
			onsetCutLen = onsetMonthDay - onsetDateDay;
		}

		expirationCutLen = expirationDateDay - 1;

		System.out.println("onsetCutLen :" + onsetCutLen);
		System.out.println("expirationCutLen :" + expirationCutLen);

		res.put("onsetCutLen", onsetCutLen);
		res.put("expirationCutLen", expirationCutLen);
		return res;
	}

	public static void main(String[] args)
	{
		PlanShiftInfoServiceImpl ss = new PlanShiftInfoServiceImpl();
		ss.acquireCutLen("2019-01-28", "2019-03-04");

	}

	@Override
	public int updatePlanShiftInfo(List<PlanShiftInfoBean> bean)
	{
		return planShiftInfoMapper.updatePlanShiftInfo(bean);
	}

}
